<template>
  <div class="map-container">
    <div id="map" ref="map" class="map"></div>
    <div class="marker" title="Marker" ref="marker"></div>
    <!--<div ref="popup" class="popup" v-show="shopPopup"></div>-->
    <div id="popup" class="popup-container">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content" class="popup-content"></div>
    </div>
  </div>
</template>
<script>
import 'ol/ol.css'
import { Map, View, Feature } from 'ol'
import Tile from 'ol/layer/Tile'
import { Style,Icon} from 'ol/style'
import { Point } from "ol/geom"
import VectorLayer from "ol/layer/Vector"
import VectorSource from "ol/source/Vector"
import XYZ from 'ol/source/XYZ' // 引入XYZ地图格式
import BingMaps from 'ol/source/BingMaps'
import markerImg from "@/assets/image/map/marker.png"
import { fromLonLat, transform, toLonLat } from 'ol/proj';
import { toStringHDMS } from 'ol/coordinate';
import Overlay from 'ol/Overlay';

// https://www.codenong.com/cs106361074
export default {
    name: "baseMap",
    props: {},
    data() {
        return {
            markerImg: markerImg,
            map:null,
            featuresArr: [],
            shopPopup: false
        }
    },

    mounted() {
        let _ = this
        _.initMap()
        let coordinates = [
            { x: "122.399", y: "31.668",info:{name:'wxb',value:1}},
            { x: "122.499", y: "31.868",info:{name:'zjj',value:2}},
            { x: "122.599", y: "31.968",info:{name:'fq',value:3}}
        ]
        this.addMarker(coordinates)
        _.addPopup()
    },
    methods: {
        // 实例化地图
        initMap() {
            let _ = this
            this.map = new Map({
                target: this.$refs.map,
                layers: [
                    // new Tile({
                    //     name: 'defaultLayer',
                    //     source: new XYZ({
                    //         url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
                    //     })
                    // })
                    new Tile({
                        source: new BingMaps({
                            key: 'AiZrfxUNMRpOOlCpcMkBPxMUSKOEzqGeJTcVKUrXBsUdQDXutUBFN3-GnMNSlso-',
                            imagerySet: 'Aerial'
                        })
                    })
                ],
                view: new View({
                    projection: "EPSG:4326",
                    center: [120.299, 31.568],
                    zoom: 8 // 地图缩放级别（打开页面时默认级别）
                })
            })
        },

        addMarker(coordinates) {
            // 设置图层
            this.flagLayer = new VectorLayer({
                source: new VectorSource()
            });
            // 添加图层
            this.map.addLayer(this.flagLayer);
            // 循环添加feature
            for (let i = 0; i < coordinates.length; i++) {
                // 创建feature，一个feature就是一个点坐标信息
                let feature = new Feature({
                    info: coordinates[i].info,
                    geometry: new Point([coordinates[i].x, coordinates[i].y])
                });
                feature.setStyle(
                    new Style({
                        // 设置图片效果
                        image: new Icon({
                            src: this.markerImg,
                            anchor: [1, 1]
                        })
                    })
                );
                this.featuresArr.push(feature);
            } // for 结束
            // 批量添加feature
            this.flagLayer.getSource().addFeatures(this.featuresArr);
        },
        addPopup(){
            let _ = this
            let container = document.getElementById('popup')
            let closer = document.getElementById('popup-closer')
            let content = document.getElementById('popup-content')
            // 创建popup覆盖层
            let popup = new Overlay({
                element: container, //绑定 Overlay 对象和 DOM 对象的
                autoPan: false, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
                autoPanAnimation: {
                    duration: 250, //自动平移效果的动画时间 9毫秒）
                },
            })
            // 关闭弹窗
            this.map.addOverlay(popup);
            closer.onclick = ()=> {
                popup.setPosition(undefined)
                closer.blur()
                return false
            }
            this.map.on('click', function (evt) {
                let feature = _.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) { return feature; });
                if (feature) {
                    console.log('feature', feature)
                    let coordinate = transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
                    // 点击尺 （这里是尺(米)，并不是经纬度）;
                    let hdms = toStringHDMS(toLonLat(evt.coordinate)); // 转换为经纬度显示
                    let info = feature.values_.info || {}
                    content.innerHTML = `
                      <div class="popup-content">
                        <div class="info">info：${info.name}11111111 </div>
                        <div class="info">value：${info.value}</div>
                      </div>
                    `
                    popup.setPosition(evt.coordinate); //把 overlay 显示到指定的 x,y坐标
                }else {
                    popup.setPosition(undefined)
                }
            });
        },
    },
    watch: {},
    computed: {},
}
</script>

<style lang="less" scoped>
@import "index.less";
</style>
